<?php
/**
 * 前台用户相关
 * @author 杨斌
 */
class memberCtrl extends lib_ctrl
{
	
    public function _init(){
		$this->member = $this->loadModel('member');
		if($_COOKIE['member_uid']!=0){
			$this->view->assign('member_info',array('member_uid'=>$_COOKIE['member_uid'],'member_name'=>$_COOKIE['member_name']));
		}
	}

    public function indexAct( )
    {
    	#已登陆，跳到首页
		if($this->member->isLogin())
		{
			if($this->isAjax()){
                exit('100');
			}else {
				$this->redirect(DOMAIN_ROOT);
				exit;
			}
		}
    	if(!empty($_POST)){
    		$username = strip_tags(trim($_POST['email']));
    		$password = trim($_POST['password']);
    		$autologin = intval($_POST['auto-login']) ? intval($_POST['auto-login']) : 0 ;
    		$result = $this->member->login($username,$password,$autologin);
    		if($result > 0 ) exit('1');
    		exit($result);
    	}
        $this->view->display( );
    }

    /*
     * 退出登录
     */
    public function logoutAct(){
    	$this->member->logout();
    	$this->redirect(DOMAIN_DOOR);
    }
    
    
    /*
     * 会员设置
     */
    public function settingsAct(){
    	$currUid = $this->member->getNowUid();
    	if(!empty($_POST)){
			$uid = $_POST['uid']?abs(intval($_POST['uid'])):'';
			$email = strip_tags(trim($_POST['email']));
			$gender = abs(intval($_POST['gender']));
    		$username = strip_tags(trim($_POST['username']));
    		$password = trim($_POST['password']);
    		$password2 = trim($_POST['password2']);
    		$mobile = strip_tags(trim($_POST['mobile']));
    		$qq = abs(intval($_POST['qq']));
    		$userConfig = $this->loadConfig('user');#加载与用户相关的配置文件
    		
    		if($uid=='' || $uid != $currUid) exit('-1');#提交的用户id不合法  	
    		if(!$email) exit('-2');#会员邮箱不能为空
    		if(!preg_match($userConfig['email_pat'], $email)) exit('-3');#会员邮箱格式不正确
    		if(!$username) exit('-4');#会员用户名不能为空
    		if(!preg_match($userConfig['name_pat'],$username)) exit('-5');#会员用户名不合法
    		if($password !=$password2) exit('-6');#确认密码与会员密码不相等
    		if(!$mobile) exit('-7');#会员手机不能为空
    		if(!preg_match($userConfig['phone_pat'],$mobile)) exit('-8'); #会员手机号码不合法
    		#if(!count($city)) exit('-9'); #会员所在城市没有选择
    		
    		if($this->member->isEmail($email) !== 1) exit('-10');#检测会员邮箱是否已存在
    		if($this->member->isName($username) !== 1) exit('-11');#检测会员昵称是否已存在
    		
    		#会员信息
    		$info['email'] = $email;
    		$info['username'] = $username;
    		if($password != '') $info['password'] = $this->member->createPasswd($password);
    		#$info['sys_citys_id'] = $city;
    		$info['mobile'] = $mobile;
    		$info['gender'] = $gender;
    		if($qq != '')$info['qq'] = $qq;
			$res = $this->member->editUser($info,$uid);    		
			if($res) exit('1');
    	}
    	if($currUid){
    		$Info = $this->member->getUser($currUid,array('member'=>'*','member_address'=>'code as add_code,realname as add_name,mobile as add_mobile,detail as add_detail')); 
    		$this->view->assign('info',$Info);
    	}
    	$this->view->assign('action','settings');
    	$this->view->display();
    }
    /*
     * 会员账户余额
     */
    public function creditAct(){
    	$this->view->assign('action','credit');
    	$this->view->display();
    }
    /*
     * 会员地址管理
     */
    public function addressAct(){
    	$currUid = $this->member->getNowUid();
    	$cityJson = self::parsejsAct( );#获取城市列表json数据
        $cityArray = $cityJson ? json_decode($cityJson,true) : array();
    	if(!empty($_POST)){
    		$username = strip_tags(trim($_POST['username']));
    		$address_id = $_POST['address_id']?abs(intval($_POST['address_id'])):0;#判断是更新还是删除
    		$city = intval($_POST['city']);
    		$province = intval($_POST['province']);
    		$locale = intval($_POST['locale']);
    		$street_address = strip_tags($_POST['street_address']);
    		$isdefault = isset($_POST['isdefault'])?intval($_POST['isdefault']):0;
    		$mobile = strip_tags(trim($_POST['mobile']));
    		$uid = intval($_POST['uid']);
    		$zipcode = intval($_POST['zipcode']);
    		$detail = $cityArray[0][$city].' '.$cityArray[$city][$province].' '.$cityArray[$province][$locale].' '.$street_address;
    		$info = array();
    		$address = $this->loadModel('memberaddress');
    		if($isdefault) $address->resetDefault($currUid);
    		if($address_id){
    			$info = array(
    				'sys_citys_id'=>$city,
    				'realname'=>$username,
	    			'code'=>$zipcode,
	    			'detail'=>$detail,
	    			'mobile'=>$mobile,
    				'isdefault'=>$isdefault,
    			);
    			$res = $address->setID($address_id)->update($info);
    			if($res) exit('2');
    		}else{
    			$info = array(
	    			'member_id'=>$uid,
	    			'sys_citys_id'=>$city,
	    			'realname'=>$username,
	    			'code'=>$zipcode,
	    			'detail'=>$detail,
	    			'mobile'=>$mobile,
	    			'createtime'=>time(),
	    			'createip'=>getIp(),
    				'isdefault'=>$isdefault,
	    		);
	    		$count = $address->setMemberID($currUid)->counts();
	    		if($count >= 5) exit('-1');  
	    		$res = $address->addAddress($info);
	    		if($res) exit('1');
	    		exit($res);
    		}
    	}
    	if($currUid){
    		$this->view->assign('uid',$currUid);
			$address = $this->loadModel('memberaddress');
			$address->setMemberID($currUid);   
			$res = $address->getAddress($currUid);
			foreach($res as $key=>$val){
				if(isset($val['detail'])){
					$tmp = explode(' ',$val['detail']);
					$res[$key]['location'] = $tmp[0] .' '.$tmp[1].' '.$tmp['2'];
					$res[$key]['street'] = $tmp[3];
				}
			}
			$this->view->assign('addressSaved',$res); 	
    	}
		$this->view->assign('citys',$cityArray[0]);
    	$this->view->assign('action','address');
    	$this->view->display();
    }
    /*
     * 收货地址删除
     */
    public function delAddressAct(){
    	$id = abs(intval($_POST['id']));
		$currUid = $this->member->getNowUid();
		if(!$id) exit('-1');#地址ID错误
		if(!$currUid) exit('-2');#会员不存在
		$address = $this->loadModel('memberaddress');
		$res = $address->setID($id)->delete();
		if($res) exit('1');
		exit($res);
    }
    
    /*
     * 会员设置默认收货地址
     * 
     */
    public function setDefaultAddressAct(){
    	$id = abs(intval($_POST['id']));
    	$currUid = $this->member->getNowUid();
    	if(!$id) exit('-1');#id错误
    	if(!$currUid) exit('-2');#会员不存在
    	$address = $this->loadModel('memberaddress');
    	$isreset = $address->resetDefault($currUid);
    	//if(!$isreset) exit('-3');#会员状态重置不成功
    	$address->setMemberID($currUid);
    	$res=$address->setDefault($id);
    	if($res) exit('1');#默认地址设置成功
    }
    
    /*
     * 会员注册
     */
    public function registerAct( )
    {
    	if(!empty($_POST)){
    		$email = strip_tags(trim($_POST['email']));
    		$username = strip_tags(trim($_POST['username']));
    		$password = trim($_POST['password']);
    		$password2 = trim($_POST['password2']);
    		$mobile = strip_tags(trim($_POST['mobile']));
    		$city = intval($_POST['city']);
    		$userConfig = $this->loadConfig('user');#加载与用户相关的配置文件
    		
    		if(!$email) exit('-1');#会员邮箱不能为空
    		if(!preg_match($userConfig['email_pat'], $email)) exit('-2');#会员邮箱格式不正确
    		if(!$username) exit('-3');#会员用户名不能为空
    		if(!preg_match($userConfig['name_pat'],$username)) exit('-4');#会员用户名不合法
    		if(!$password) exit('-5');#会员密码不能为空
    		if($password !=$password2) exit('-6');#确认密码与会员密码不相等
    		if(!$mobile) exit('-7');#会员手机不能为空
    		if(!preg_match($userConfig['phone_pat'],$mobile)) exit('-8'); #会员手机号码不合法
    		if(!count($city)) exit('-9'); #会员所在城市没有选择
    		
    		if($this->member->isEmail($email) !== 1) exit('-10');#检测会员邮箱是否已存在
    		if($this->member->isName($username) !== 1) exit('-11');#检测会员昵称是否已存在
    		
    		#会员信息
    		$info['email'] = $email;
    		$info['username'] = $username;
    		$info['password'] = $this->member->createPasswd($password);
    		$info['sys_citys_id'] = $city;
    		$info['mobile'] = $mobile;
    		$info['createip'] = getIp();
    		$info['createtime'] = time();
    		$res = $this->member->addUser($info);
    		if($res){
    			exit('1');
    		}
    	}
    	
        $cityJson = self::parsejsAct( );#获取城市列表json数据
        $cityArray = $cityJson ? json_decode($cityJson,true) : array();
		$this->view->assign('citys',$cityArray[0]);
        $this->view->display( );
    }
    /*
     * 解析城市列表
     */
    public function parsejsAct( )
    {
        $jsfile = DOMAIN_SRC . 'js/city.js';
        $jsstr = '';
        if(!file_get_contents($jsfile)){
        	#从数据库中获取
        }else{
            ob_start( );
            readfile($jsfile);
            $output = ob_get_clean( );
            return $output;
        }
        return false;
    }
    /*
     * Ajax方式  获取下级城市
     */
    public function getCityChildrenAct(){
    	$cityJson = self::parsejsAct();
    	$cityArray = $cityJson ? json_decode($cityJson,true):array();
    	$cityid = intval($_POST['cityid']);
    	if($cityArray[$cityid]){
    		foreach($cityArray[$cityid] as $key=>$value){
    			$tmp[] = array('id'=>$key,'name'=>$value);
    		}
    		echo json_encode($tmp);
    	}
    	exit(1);
    }  
}